package session

import (
	"github.com/satori/go.uuid"
	"sync"
)

type MemorySessionMgr struct {
	sessionMap map[string]Session
	rwMutex    sync.RWMutex
}

func NewMemorySessionMgr() SessionMgr {
	return &MemorySessionMgr{
		sessionMap: make(map[string]Session, 1024),
		rwMutex:    sync.RWMutex{},
	}
}

func (smgr *MemorySessionMgr) Get(sessionId string) (session Session, err error) {
	smgr.rwMutex.RLock()
	defer smgr.rwMutex.RUnlock()
	session, ok := smgr.sessionMap[sessionId]
	if !ok {
		err = ErrSessionNotExist
	}
	return
}

func (smgr *MemorySessionMgr) CreateSession() (session Session, err error) {
	smgr.rwMutex.Lock()
	defer smgr.rwMutex.Unlock()
	id, err := uuid.NewV4()
	if err != nil {
		return
	}
	sessionId := id.String()
	session = NewMemorySession(sessionId)
	smgr.sessionMap[sessionId] = session
	return
}

func (smgr *MemorySessionMgr) Init(adress string, options ...interface{}) error {
	return nil
}
